package cn.itsource.basic.service.impl;

import cn.itsource.basic.constant.PetHomeConstant;
import cn.itsource.basic.service.IVerificationCodeService;
import cn.itsource.basic.util.SendMesUtils;
import cn.itsource.basic.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    @Autowired
    private  RedisTemplate redisTemplate;
    //获取注册验证码
    @Override
    public void sendMobileCode(String phone) {
       sendMobileCode(phone, PetHomeConstant.REGISTER_VERIFICATION_CODE);
    }
    //获取微信绑定验证码
    @Override
    public void sendBinderMobileCode(String phone) {
        sendMobileCode(phone,PetHomeConstant.BINDER_VERIFICATION_CODE );
    }

    public void sendMobileCode(String phone,String type){
        //获取四位随机数
        String code = StrUtils.getRandomString(4);
        //从redis中获取之前的随机数   os80:1234343443
        String oldCode = (String)redisTemplate.opsForValue().get(type +":"+ phone);
        //判断oldCode是否存在
        if(!StringUtils.isEmpty(oldCode)){//不为空，证明里面已产生过随机数
            //获取第一次生成随机数的毫秒值
            Long oldTime= Long.valueOf(oldCode.split(":")[1]);
            //判断redis中的值是否存在了一分钟
            if(System.currentTimeMillis()-oldTime<60*1000){//小于一分钟
                //抛出异常不要再试
                throw new RuntimeException("一分钟以内不要重复获取验证码");
            }
            //在超过一分钟但是在五分钟以内，设置随机数为原来的随机数
            code=oldCode.split(":")[0];
        }
        //把验证码存入redis中
        redisTemplate.opsForValue().set(type+":"+phone, code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
        //通过网建发送短信
        String content = "尊敬的用户，你的验证码为:"+code+",请在5分钟以内完成验证操作!!";
        System.out.println(code);
        /*SendMesUtils.sendMes(phone, content);*/
    }
}
